package com.gsp.gspframework.helper;

import com.gsp.gspframework.annotation.Action;
import com.gsp.gspframework.bean.Handler;
import com.gsp.gspframework.bean.Request;
import org.apache.commons.lang3.ArrayUtils;
import java.lang.reflect.Method;
import java.util.*;

public final class ControllerHelper {

    private static final Map<Request, Handler> ACTION_MAP = new HashMap<>();

    static {
        Set<Class<?>> classSet = ClassHelper.getControllerClassSet();
        classSet.stream().forEach((clz -> {
            Method[] methods = clz.getDeclaredMethods();
            Arrays.stream(methods).forEach((method -> {
                if (method.isAnnotationPresent(Action.class)) {
                    Action action = method.getAnnotation(Action.class);
                    String mapping = action.value();
                    if (mapping.matches("\\w+:/\\w*")) {
                        String[] array = mapping.split(":");
                        if (ArrayUtils.isNotEmpty(array) && array.length == 2) {
                            Handler handler = new Handler(clz, method);
                            ACTION_MAP.put(new Request(array[0], array[1]), handler);
                        }
                    }
                }
            }));
        }));
    }

    public static Handler getHandler(String requestMethod, String requestPath) {
        return ACTION_MAP.get(new Request(requestMethod, requestPath));
    }


}
